import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:meco/common/index.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'package:meco/views/me/me/controller.dart';

class SetupController extends GetxController {
  SetupController();

  // 用户服务
  final UserService _userService = Get.find<UserService>();

  // 用户仓库
  final UserRepository _userRepository = UserRepository();

  // 当前用户
  final Rx<User?> currentUser = Rx<User?>(null);

  // 初始化数据
  _initData() {
    // 获取当前登录用户
    currentUser.value = _userService.currentUser.value;
    update(["setup"]);
  }

  // 退出登录
  Future<void> logout() async {
    try {
      EasyLoading.show(status: 'Logging out...');

      // 调用用户服务的退出登录方法
      await _userService.logout();

      EasyLoading.dismiss();
      EasyLoading.showSuccess('Logged out successfully');

      // 延迟返回主页
      Future.delayed(Duration(milliseconds: 1500), () {
        // 返回主页
        Get.back();
      });
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError('Logout failed, please try again');
      print('退出登录失败: $e');
    }
  }

  // 隐私政策
  void privacyPolicy() async {
    final Uri url = Uri.parse('https://www.example.com/privacy-policy');
    if (!await launchUrl(url)) {
      EasyLoading.showError('Could not launch the privacy policy page');
    }
  }

  // 服务条款
  void termsOfService() async {
    final Uri url = Uri.parse('https://www.example.com/terms-of-service');
    if (!await launchUrl(url)) {
      EasyLoading.showError('Could not launch the terms of service page');
    }
  }

  // EULA
  void eula() async {
    final Uri url = Uri.parse('https://www.example.com/eula');
    if (!await launchUrl(url)) {
      EasyLoading.showError('Could not launch the EULA page');
    }
  }

  // 修改头像
  Future<void> changeAvatar() async {
    if (currentUser.value == null) {
      EasyLoading.showError('User not logged in');
      return;
    }

    try {
      // 使用ImagePicker选择图片
      final ImagePicker picker = ImagePicker();
      final XFile? image = await picker.pickImage(source: ImageSource.gallery);

      if (image == null) return; // 用户取消选择

      EasyLoading.show(status: 'Updating avatar...');

      // 使用copyWith方法更新用户头像
      final User updatedUser = currentUser.value!.copyWith(
        avatar: image.path,
        updatedAt: DateTime.now(),
      );

      // 调用API保存用户信息
      final result = await _userRepository.updateUser(updatedUser);

      if (result != null) {
        // 更新本地用户信息
        currentUser.value = updatedUser;

        // 更新UserService中的用户信息
        _userService.currentUser.value = updatedUser;

        // 刷新UI
        update(["setup"]);

        // 通知Me页面更新
        if (Get.isRegistered<MeController>()) {
          Get.find<MeController>().initData();
          Get.find<MeController>().update(["me_page"]);
        }

        EasyLoading.dismiss();
        EasyLoading.showSuccess('Avatar updated successfully');
      } else {
        EasyLoading.dismiss();
        EasyLoading.showError('Failed to update avatar');
      }
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError('Error updating avatar: $e');
      print('更新头像失败: $e');
    }
  }

  // 修改个人资料（包括头像）
  void editProfile() {
    Get.toNamed(Routes.information);
  }

  // 删除账户
  void deleteAccount() {
    Get.dialog(
      AlertDialog(
        title: Text('Delete Account'),
        content: Text(
          'Are you sure you want to delete your account? This action cannot be undone.',
        ),
        actions: [
          TextButton(onPressed: () => Get.back(), child: Text('Cancel')),
          TextButton(
            onPressed: () {
              Get.back();
              // 这里应该添加删除账户的逻辑
              EasyLoading.showInfo('This feature is not implemented yet');
            },
            child: Text('Delete', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }

  @override
  void onInit() {
    super.onInit();
    _initData();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }
}
